<template>
  <div class="app-recycle-content">
    <div class="button-group">
      <el-button class="clear" plain @click="deleteSelectedFiles">
        <img src="../../assets/清空回收站.png" style="width: 20px; height: 20px; margin-right: 5px;">删除
      </el-button>
      <el-button class="restore" plain @click="restoreFiles">
        <img src="../../assets/恢复.png" style="width: 20px; height: 20px; margin-right: 5px;">恢复
      </el-button>
      <el-input v-model="keyword" placeholder="请输入回收ID" style="width: 200px; margin-left: 20px;">
      </el-input>
      <el-button class="search" plain @click="searchFile" style="margin-left: 10px;">
        <img src="../../assets/search.png" style="width: 20px; height: 20px; margin-right: 5px;">搜索
      </el-button>
    </div>

    <div class="recycle-bin">
      <div v-if="files.length === 0" class="empty">
        <div class="icon">
          <img src="../../../src/assets/huishouzhan.png" alt="回收站" />
        </div>
        <h2>您的回收站为空 ~</h2>
        <p>回收站为您保存10天内删除的文件，超过10天的文件将会永久删除。</p>
      </div>
      <el-table :data="files" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="recycle" label="回收ID" width="200"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="200"></el-table-column>
        <el-table-column prop="file" label="文件ID" width="200"></el-table-column>
        <el-table-column prop="deletedTime" label="创建时间" width="250"></el-table-column>
        <el-table-column prop="updatedTime" label="更新时间" width="250"></el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
      :current-page="queryParams.pageNum" :page-sizes="[1, 5, 10]" :page-size="queryParams.pageSize"
      @size-change="handleSizeChange" @current-change="handlePageChange" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import axios from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

// 分页参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 5,
});

const total = ref(0); // 文件总数
const files = ref([]); // 文件数据
const keyword = ref(""); // 搜索关键字
const selectedFiles = ref([]); // 保存选中的文件

// 从 localStorage 中获取 token 并解析 userId
const token = localStorage.getItem("token");
let userId = 0;

// 假设解析 token 的逻辑
if (token) {
  try {
    const parsedToken = JSON.parse(atob(token.split(".")[1])); // 假设 token 是 JWT 格式
    userId = parsedToken.userId || 0;
  } catch (error) {
    console.error("Token 解析失败:", error);
    userId = 1; // 如果解析失败，设置为 0 或其他默认值
  }
} else {
  userId = 2; // 假设没有 token，手动设置一个假 userId
}

const fetchTableData = async () => {
  try {
    const response = await axios.get(`/reclaim/user/${userId}`, { // 使用反引号
      params: {
        pageNum: queryParams.value.pageNum,
        pageSize: queryParams.value.pageSize,
        keyword: keyword.value.trim(),
      },
    });


    // 检查接口返回是否成功
    if (response.code === 200) {
      const records = response.data.records || [];
      files.value = records.map((file) => ({
        recycle: file.reclaimId || "", // 映射到回收ID
        userId: file.homeFileId || "", // 映射到用户ID
        file: file.fileId || "", // 映射到文件ID
        deletedTime: file.createTime || "", // 映射到创建时间
        updatedTime: file.updateTime || "", // 映射到更新时间
      }));
      total.value = response.data.total || 0; // 更新总记录数
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("无法加载数据，请稍后重试。");
  }
};

// 搜索文件
const searchFile = () => {
  queryParams.value.pageNum = 1; // 重置到第一页
  fetchTableData();
};

// 分页处理
const handleSizeChange = (newPageSize) => {
  queryParams.value.pageSize = newPageSize;
  fetchTableData();
};

const handlePageChange = (newPageNum) => {
  queryParams.value.pageNum = newPageNum;
  fetchTableData();
};

// 处理表格选择事件
const handleSelectionChange = (selected) => {
  selectedFiles.value = selected.map((file) => file.recycle);
};

// 删除选中的文件
const deleteSelectedFiles = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请先选择要删除的文件");
    return;
  }

  // 打印选中的文件ID进行调试
  console.log("选中的文件ID:", selectedFiles.value);

  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedFiles.value.length} 个文件吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await axios.delete("/reclaim/delete", {
      params: { reclaims: selectedFiles.value.join(",") },
    });


    console.log("删除响应:", response); // 打印完整的响应，检查数据

    if (response.code === 200) {
      ElMessage.success(response.msg || "删除成功");
      fetchTableData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "删除失败");
    }
  } catch (error) {
    console.log("删除操作被取消或失败:", error);
  }
};


// 恢复选中的文件
const restoreFiles = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning("请先选择要恢复的文件");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确认恢复选中的 ${selectedFiles.value.length} 个文件吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 如果用户点击“确定”，执行恢复逻辑
    const response = await axios.post("/file/restore", null, {
      params: {
        reclaims: selectedFiles.value.join(",")  // 传递回收ID
      }
    });

    if (response.code === 200) {
      ElMessage.success(response.msg || "恢复成功");
      fetchTableData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "恢复失败");
    }
  } catch (error) {
    console.log("恢复操作被取消或失败:", error);
  }
};


// 初始化加载数据
onMounted(fetchTableData);
</script>


<style scoped>
.button-group {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.el-button {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border-radius: 5px;
  border: none;
  font-size: 14px;
}

.el-button img {
  filter: brightness(0) invert(1);
  /* 白色图标 */
}

/* 按钮颜色样式 */
.el-button.clear {
  background-color: #f56c6c;
  /* 红色 */
}

.el-button.restore {
  background-color: #67c23a;
  /* 绿色 */
}

.el-button.search {
  background-color: #409eff;
  /* 蓝色 */
}

.el-input {
  border-radius: 5px;
  font-size: 14px;
}

.recycle-bin {
  padding: 0px;
  background-color: #f3f4f6;
  border-radius: 10px;
}

.recycle-bin .empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 100px);
  /* 减去顶部的操作区域高度 */
  text-align: center;
  color: #999;
}

.icon img {
  width: 120px;
  /* 图标大小 */
  height: 120px;
  margin-bottom: 15px;
}

h2 {
  font-size: 26px;
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
}

p {
  color: #666;
  margin: 5px 0;
}

.table-container {
  background: white;
  padding: 20px;
  border-radius: 10px;
}

.el-table {
  border-radius: 10px;
  overflow: hidden;
}

.el-table-column {
  text-align: center;
}

.el-table th,
.el-table td {
  font-size: 14px;
  color: #555;
}

.el-table .el-checkbox__inner {
  border-color: #409eff;
}
</style>